#!/bin/bash

set -e

ARCHIVE=live.2025.11.06.tar.gz
LIBHELIXAAC_VER=2.4.1
ARCHIVE_LIBHELIXAAC=${LIBHELIXAAC_VER}.tar.gz

export CROSSPATH=/opt/yi/toolchain-sunxi-musl/toolchain/bin
export PATH=${PATH}:${CROSSPATH}

export TARGET=arm-openwrt-linux
export CROSS=arm-openwrt-linux
export BUILD=x86_64-pc-linux-gnu

export CROSSPREFIX=${CROSS}-

export STRIP=${CROSSPREFIX}strip
export CXX=${CROSSPREFIX}g++
export CC=${CROSSPREFIX}gcc
export LD=${CROSSPREFIX}ld
export AS=${CROSSPREFIX}as
export AR=${CROSSPREFIX}ar

SCRIPT_DIR=$(cd `dirname $0` && pwd)
cd $SCRIPT_DIR

rm -rf ./_install
rm -rf ./live
rm -rf ./fdk-aac
rm -rf ./libhelix-aac

# fdk-aac
if [ ! -f ${ARCHIVE_LIBHELIXAAC} ]; then
    wget https://github.com/earlephilhower/ESP8266Audio/archive/refs/tags/${ARCHIVE_LIBHELIXAAC}
fi
tar zxvf ${ARCHIVE_LIBHELIXAAC}
mv ESP8266Audio-${LIBHELIXAAC_VER}/src/libhelix-aac libhelix-aac
patch -p0 < not-arduino.patch
patch -p0 < remove-mangling.patch
cd libhelix-aac
wget https://raw.githubusercontent.com/FrankBoesing/Arduino-Teensy-Codec-lib/refs/heads/master/aac/armgcc_nosyms/sbrcov.S
sed -i -e 's/raac_CVKernel1/CVKernel1/g' sbrcov.S
sed -i -e 's/raac_CVKernel2/CVKernel2/g' sbrcov.S
cd ..
rm -rf ESP8266Audio-${LIBHELIXAAC_VER}
cp Makefile.libhelix-aac libhelix-aac/Makefile

# live555
if [ ! -f $ARCHIVE ]; then
    wget https://download.videolan.org/pub/contrib/live555/$ARCHIVE
fi
tar zxvf $ARCHIVE
find live -type d -exec chmod 755 {} +
find live -type f -name "*.cpp" -exec chmod 644 {} +
find live -type f -name "*.hh" -exec chmod 644 {} +
find live -type f -name "Makefile*" -exec chmod 644 {} +

patch -p0 < rRTSPServer.patch
patch -p0 < friend.patch

cd live || exit 1

./genMakefiles linux-cross
cp -f ../Makefile.rRTSPServer Makefile
cp -rf ../src .
cp -rf ../include .
